<script setup lang="tsx">
import { register } from '@tauri-apps/plugin-global-shortcut';
import { onMounted, reactive } from 'vue';
import { TrayIcon } from '@tauri-apps/api/tray';
import { Menu } from '@tauri-apps/api/menu';
import { defaultWindowIcon } from '@tauri-apps/api/app';
import Content from './modules/content.vue';
import Floater from './modules/floater.vue';
import { Window } from '@tauri-apps/api/window';

const currentWindow = Window.getCurrent();
const state = reactive({
  pageStatus: 'main'
})
const bindShortCut = async () => {
  await register('ctrl+q', async() => {
    state.pageStatus = 'floater';
    setTimeout(async () => {
      await currentWindow.show();
      await currentWindow.setFocus();
    }, 100);
  });
  await register('shift + esc', async() => {
    state.pageStatus = 'main';
    setTimeout(async () => {
      await currentWindow.show();
      await currentWindow.setFocus();
    }, 100);
  });
}

const clickQuit = async () => {
  await currentWindow.close();
};
const clickHideInTray = async () => {
  await currentWindow.hide();
};
const menu = await Menu.new({
  items: [
    {
      id: 'hide-in-tray',
      text: '隐藏到托盘',
      action: clickHideInTray
    },
    {
      id: 'show-mini',
      text: '显示小窗口(ctrl+q)',
      action: () => {
        state.pageStatus = 'floater';
        setTimeout(async () => {
          await currentWindow.show();
          await currentWindow.setFocus();
        }, 100)
      }
    },
    {
      id: 'quit',
      text: '退出',
      action: clickQuit
    }
  ]
});
const setTray = async () => {
  await TrayIcon.new({
    icon: await defaultWindowIcon(),
    menu,
    showMenuOnLeftClick: false,
    action: event => {
      switch (event.type){
        case 'DoubleClick':
          currentWindow.show();
          state.pageStatus = 'main';
          setTimeout(async () => {
            await currentWindow.setFocus();
          }, 100);
          break;
      }
    }
  })
}

onMounted(() => {
  bindShortCut();
  setTray();
});
</script>

<template>
  <div class="home-container h-100%">
    <Content v-if="state.pageStatus === 'main'" />
    <Floater v-if="state.pageStatus === 'floater'" />
  </div>
</template>

<style scoped>

</style>